import { Request, Response } from 'express';
import jwt from 'jsonwebtoken';
import { JWT_SECRET } from '../../middleware/auth';
import { verifyCaptcha } from './utils';
import { CustomSession } from '../../types/auth';
import logger from '../../utils/logger';
import { adminUserService } from '../adminUser/service';

interface AuthRequest extends Request {
    session: CustomSession;
    user?: {
        id: string;
    };
}

interface LoginBody {
    username: string;
    password: string;
    captcha: string;
}

interface ChangePasswordBody {
    oldPassword: string;
    newPassword: string;
}

const generateToken = (user: any): string => {
    return jwt.sign(
        {
            id: user.id,
            username: user.username,
            nickname: user.nickname,
        },
        JWT_SECRET,
        { expiresIn: '24h' }
    );
};

async function login(req: AuthRequest & { body: LoginBody }, res: Response) {
    const { username, password, captcha } = req.body;

    if (!username || !password || !captcha) {
        return res.status(400).json({
            success: false,
            error: '请填写完整的登录信息'
        });
    }

    const captchaResult = verifyCaptcha(req.session, captcha);
    logger.info("---------verifyCaptcha", captchaResult);
    if (!captchaResult.success) {
        return res.status(400).json(captchaResult);
    }

    try {
        const user = await adminUserService.login(username, password);
        logger.info("---------user", user);
        if (!user) {
            return res.status(400).json({
                success: false,
                error: '用户名或密码错误'
            });
        }

        if (!user.id) {
            throw new Error('Invalid user ID');
        }
        //判断用户状态是否可以登录
        if (user.status !== 1) {
            throw new Error('该用户状态不正确，请联系管理员！');
        }

        //获取用户的权限
        const promise = await adminUserService.findById(Number(user.id));
        let permissions: string[] = []; // 默认为空数组
        logger.info("promise", promise);

        await adminUserService.updateLoginInfo(user.id, req.ip || '');

        // 创建包含所需信息的对象
        const userInfo: any = {
            ...adminUserService.toUserInfo(user),
            token: '' // 先初始化为空字符串
        };

        // 生成 token 并添加到 userInfo
        userInfo.token = generateToken(userInfo);

        req.session.user = userInfo;

        res.json({
            success: true,
            message: '登录成功',
            data: userInfo
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: '登录失败',
            error: error instanceof Error ? error.message : String(error)
        });
    }
}

async function changePassword(req: AuthRequest & { body: ChangePasswordBody }, res: Response) {
    try {
        const { oldPassword, newPassword } = req.body;
        const userId = Number(req.user?.id);

        if (!userId) {
            return res.status(401).json({
                success: false,
                message: '未授权的访问'
            });
        }

        if (!oldPassword || !newPassword) {
            return res.status(400).json({
                success: false,
                message: '旧密码和新密码为必填项'
            });
        }

        const success = await adminUserService.changePassword(userId, oldPassword, newPassword);
        if (!success) {
            return res.status(400).json({
                success: false,
                message: '旧密码错误或用户不存在'
            });
        }

        req.session.user = undefined;
        req.session.destroy((err) => {
            if (err) {
                console.error('清除session失败:', err);
            }
        });

        res.json({
            success: true,
            message: '密码修改成功，请重新登录'
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: '修改密码失败',
            error: error instanceof Error ? error.message : String(error)
        });
    }
}

async function logout(req: AuthRequest, res: Response) {
    req.session.user = undefined;
    return res.json({ success: true });
}

async function getUserInfo(req: AuthRequest, res: Response) {
    const userInfo = req.session.user;
    res.json({ data: userInfo });
}

export {
    login,
    logout,
    getUserInfo,
    changePassword
};